package com.ezops.poc.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ezops.poc.bo.DynamicModel.Field;
import com.ezops.poc.bo.IClientModel;

/**
 * This is the default strategy for persisting the client Model. The key fields
 * present in super class {@code IClientModel} will be stored in separate column
 * and all other fields will be stored as json in a column name data.
 * 
 * @author vgaurav
 * 
 */
public class DefaultClientFilePersistanceStrategy implements
		EzopsPersistanceStrategy<IClientModel> {

	private static final Logger logger = LoggerFactory
			.getLogger(DefaultClientFilePersistanceStrategy.class);

	private static final String COMMA_SEPARATED_COLUMNS = "EZOPS_ID,BATCH_ID,CLIENT_ID,ASSET_ID,CLIENT_TRADE_ID,ACTION, FILE_NAME,STATUS,PROCESSED_DATE, CLIENT_DATA";

	private static final String INSERT_CLIENT_MODEL_QUERY = "INSERT INTO EZOPSDB.CLIENT_TRADES( "
			+ COMMA_SEPARATED_COLUMNS
			+ ")"
			+ " VALUES "
			+ "(?,?,?,?,?,?,?,?,?,?)";

	/**
	 * Generate the insert query. This implementation doesn't depends on the
	 * type of model or client and asset combination.
	 */
	@Override
	public String getQuery() {

		logger.debug("Returning -" + INSERT_CLIENT_MODEL_QUERY);

		return INSERT_CLIENT_MODEL_QUERY;
	}

	/**
	 * Return the column values.
	 */
	@Override
	public Object[] getColumnValues(IClientModel model) {
		logger.trace("Returning the values of client trade to be persisted.");
		return new Object[] { 0,model.getBatchId(), model.getClientId(),
				model.getAssetId(), model.getClientTradeId(),
				model.getAction(), model.getFileName(), model.getTradeStatus().getStatus(),
				model.getProcessedDate(), getData(model)

		};
	}

	/**
	 * Return the json representation of al other fields to be stored in
	 * client_data column.
	 * 
	 * @param model
	 * @return
	 */
	private Object getData(IClientModel model) {
		Iterator<Field> iterator = model.iterator();
		Map<String, String> map = new HashMap<>();

		while (iterator.hasNext()) {
			Field field = iterator.next();
			map.put(field.getName(), field.getValue());
		}
		return new JSONObject(map).toString();

	}

}
